/**
 * 压缩图片到目标大小（约1MB）
 * @param {File} file - 图片文件对象
 * @param {Object} [options] - 压缩选项
 * @param {number} [options.targetSize=1024*1024] - 目标大小（字节）
 * @param {number} [options.maxWidth=1920] - 最大宽度
 * @param {number} [options.maxHeight=1080] - 最大高度
 * @param {number} [options.initialQuality=0.9] - 初始压缩质量
 * @param {number} [options.minQuality=0.5] - 最低压缩质量
 * @returns {Promise<File>} - 压缩后的图片文件
 */
export async function compressImage(file, options = {}) {
  // 设置默认选项
  const {
    targetSize = 1024 * 1024, // 1MB
    maxWidth = 1920,
    maxHeight = 1080,
    initialQuality = 0.9,
    minQuality = 0.5
  } = options;

  // 如果图片已经小于目标大小，直接返回
  if (file.size <= targetSize) {
    return file;
  }

  // 创建图片对象
  const img = new Image();
  const imgSrc = URL.createObjectURL(file);
  
  // 等待图片加载
  await new Promise((resolve) => {
    img.onload = resolve;
    img.src = imgSrc;
  });

  // 计算新尺寸（保持宽高比）
  let width = img.width;
  let height = img.height;
  
  if (width > maxWidth) {
    height = Math.round((height * maxWidth) / width);
    width = maxWidth;
  }
  
  if (height > maxHeight) {
    width = Math.round((width * maxHeight) / height);
    height = maxHeight;
  }

  // 创建Canvas进行压缩
  const canvas = document.createElement('canvas');
  canvas.width = width;
  canvas.height = height;
  
  const ctx = canvas.getContext('2d');
  ctx.drawImage(img, 0, 0, width, height);
  
  // 释放图片URL
  URL.revokeObjectURL(imgSrc);

  // 压缩函数
  const compress = (quality) => {
    return new Promise((resolve) => {
      canvas.toBlob(
        (blob) => resolve(blob),
        'image/jpeg',
        quality
      );
    });
  };

  // 尝试压缩（质量递减）
  let quality = initialQuality;
  let compressedBlob = await compress(quality);
  
  while (compressedBlob.size > targetSize && quality > minQuality) {
    // 每次减少10%的质量
    quality -= 0.1;
    compressedBlob = await compress(quality);
  }

  // 如果仍然太大，尝试缩小尺寸
  if (compressedBlob.size > targetSize) {
    canvas.width = Math.round(width * 0.9);
    canvas.height = Math.round(height * 0.9);
    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    compressedBlob = await compress(minQuality);
  }

  // 转换为File对象
  return new File([compressedBlob], file.name, {
    type: 'image/jpeg',
    lastModified: Date.now()
  });
}